﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows;

namespace MaskDemo
{
    public class PopupAdorner : Adorner
    {
        private readonly VisualCollection _visuals;
        private readonly Grid _container;
        private readonly FrameworkElement _content;

        public Action CloseCallback { get; set; }
        public Brush MaskBrush { get; set; }
        public bool CloseOnClickMask { get; set; }

        public PopupAdorner(UIElement adornedElement, FrameworkElement content)
            : base(adornedElement)
        {
            _content = content;
            _container = CreateContainer();
            _visuals = new VisualCollection(this) { _container };
        }

        private Grid CreateContainer()
        {
            var grid = new Grid();

            // 创建遮罩层
            var mask = new Rectangle
            {
                Fill = new SolidColorBrush(Colors.Black),
                Opacity = 0.7
            };

            if (CloseOnClickMask)
            {
                mask.MouseDown += (s, e) => Close();
            }

            // 设置弹窗内容
            _content.VerticalAlignment = VerticalAlignment.Center;
            _content.HorizontalAlignment = HorizontalAlignment.Center;
            _content.Margin = new Thickness(20);

            grid.Children.Add(mask);
            grid.Children.Add(_content);

            return grid;
        }

        public void Close()
        {
            var layer = AdornerLayer.GetAdornerLayer(AdornedElement);
            layer?.Remove(this);
            CloseCallback?.Invoke();
        }

        // 以下为Adorner必须实现的成员
        protected override int VisualChildrenCount => _visuals.Count;
        protected override Visual GetVisualChild(int index) => _visuals[index];

        protected override Size MeasureOverride(Size constraint)
        {
            _container.Measure(constraint);
            return base.MeasureOverride(constraint);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _container.Arrange(new Rect(finalSize));
            return base.ArrangeOverride(finalSize);
        }
    }
}
